package com.blue.gateway.paycore.alipay.bill;

import com.alibaba.fastjson.JSON;
import com.blue.gateway.common.Request;
import com.blue.gateway.common.request.BillRequest;
import com.blue.gateway.config.AliConfig;
import com.blue.gateway.config.BaseChannelConfig;
import com.blue.gateway.dto.Result;
import com.blue.gateway.dto.ResultWrapper;
import com.blue.gateway.enums.PayChannelEnum;
import com.blue.gateway.enums.ResultCodeEnum;
import com.blue.gateway.utils.http.HttpClientsUtil;
import com.blue.gateway.annotation.Channel;
import com.blue.gateway.common.response.BillResponse;
import com.blue.gateway.paycore.alipay.AliMethodEnum;
import com.blue.gateway.paycore.alipay.AliPayConstants;
import com.blue.gateway.paycore.alipay.pay.AliPayService;
import com.blue.gateway.enums.ServiceChannelEnum;
import com.blue.gateway.utils.DateUtil;
import com.blue.gateway.utils.WebUtil;
import com.blue.gateway.utils.sign.AliPaySignature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author xiaoyiming
 * @date 2020/5/4 14:45
 * @depiction https://opendocs.alipay.com/apis/api_1/alipay.trade.page.pay/
 */
@Slf4j
@Channel(PayChannel = PayChannelEnum.ALIPAY, ServiceChannel = ServiceChannelEnum.BILL_DOWNLOAD)
public class AliPayBillService extends AliPayService {

    @Override
    public Result validate(Request request) {
        BillRequest billRequest = (BillRequest) request;
        if (StringUtils.isEmpty(billRequest.getBillType())) {
            return ResultWrapper.fail(ResultCodeEnum.PARAM_ILLEGAL);
        }
        if (StringUtils.isEmpty(billRequest.getBillDate())) {
            return ResultWrapper.fail(ResultCodeEnum.PARAM_ILLEGAL);
        }
        return ResultWrapper.success();
    }

    @Override
    public BaseChannelConfig getConfig(Request request) {
        return super.getConfig(request);
    }

    @Override
    public String generateParams(Request request, BaseChannelConfig channelConfig) {
        BillRequest payRequest = (BillRequest) request;
        AliConfig aliConfig = (AliConfig) channelConfig;

        //公共请求参数
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("app_id", aliConfig.getAppId());
        paramMap.put("method", AliMethodEnum.BILL_DOWNLOADURL_QUERY.getMethodName());
        paramMap.put("charset", AliPayConstants.CHARSET_UTF8);
        paramMap.put("sign_type", aliConfig.getSignType());
        paramMap.put("timestamp", DateUtil.formatDateYMDHMS(new Date()));
        paramMap.put("version", AliPayConstants.VERSION);
        paramMap.put("notify_url", payRequest.getNotifyUrl());
        if (StringUtils.isNotBlank(payRequest.getReturnUrl())) {
            paramMap.put("return_url", payRequest.getReturnUrl());
        }

        //请求参数 biz_content
        SortedMap<String, String> contentMap = new TreeMap<>();
        contentMap.put("bill_type", payRequest.getBillType());
        contentMap.put("bill_date", payRequest.getBillDate());

        paramMap.put("biz_content", JSON.toJSONString(contentMap));

        //参数加密
        String sign = AliPaySignature.sign(paramMap, aliConfig.getPrivateKey());
        paramMap.put("sign", sign);

        return AliPayConstants.GATEWAY_URL + WebUtil.getRequestUrl(paramMap);
    }

    @Override
    public String execute(String requestParams, BaseChannelConfig channelConfig) {
        String result = null;
        try {
            result = HttpClientsUtil.httpClientGet(requestParams);
        } catch (Exception e) {
            // do nothing
        }
        return result;
    }

    /**
     * 异常数据:
     * {
     * "alipay_data_dataservice_bill_downloadurl_query_response":{
     * "code":"40004",
     * "msg":"Business Failed",
     * "sub_code":"isv.invalid_arguments",
     * "sub_msg":"入参不合法"
     * },
     * "sign":"TJPVaM4KoFTgyOfGXzQylu0givWTRUWrywWMeabI/RBccqcpgptaF6KS6sq7iLXEx+RiN6w6XP77tMGx/FtNCS8CmGFs9XbBEie7VBcErJ25xhZVNVIEW/3CwY4Uj4jOFx33A1FAiVWebxpyumHxA902s1bzk5cTVQX7Kn0qoA//1oBzj51wW+XEzowftCJN0fMGO2BDTt4mMX5jxRnRakmZ0HSBn+ZDkROp6MwZCOW/4MtKZLAMnmpqAz5y4TBcVrC2/NJ+wUDvId3U6bVJbtC7JBpBvQ/aTwaNf/KJGmbHpw6F3/uOOYFE5U1IzJczhY/mCHXz2qfYKZmfH6EpMQ=="
     * }
     * 正常数据:
     * {
     * "alipay_data_dataservice_bill_downloadurl_query_response":{
     * "code":"10000",
     * "msg":"Success",
     * "bill_download_url":"http://dwbillcenter.alipay.com/downloadBillFile.resource?bizType=trade&userId=20887212071639400156&fileType=csv.zip&bizDates=20200504&downloadFileName=20887212071639400156_20200504.csv.zip&fileId=%2Ftrade%2F20887212071639400156%2F20200504.csv.zip×tamp=1588673458&token=ff92a9666cbea47b5645b66c63275f70"
     * },
     * "sign":"dkVoPpsAQjuK3eHLUBP6uVPcFwTn25PMbTqAQeaiz2bsV/I3DSMp0In0jLEN7NN0/idEUYCl6T6KHLbtLF2/x5/aE28IH4ud+zW6GTbiU4OSwuEtN2/Un0uPjK5H8YQjd1U5Nd8XkjzhYqy5E7EQxPL6En2w+2JpV0UpUl3o1cUWczklGj8ecS9tHnMGwbF/EYq0u0lMbaOZxLAblWdxtJ0eocs5aB4ak0y1BeFe1HkxSgmNVCtxb9ItxGGdLbDMLoa+SG458B60yw8RteeotE0JGt5y/WvuUds0oqQRFnf1gd9f98XYsILhJHYZhC28s55JK9teuyCAuytNssZ9RQ=="
     * }
     *
     * @param executeResult
     * @return
     */
    @Override
    public Result<BillResponse> analysisResult(String executeResult) {
        Map resultMap = JSON.parseObject(executeResult);
        Map map = JSON.parseObject(String.valueOf(resultMap.get(AliMethodEnum.BILL_DOWNLOADURL_QUERY.getResponseName())));
        String code = String.valueOf(map.get("code"));
        BillResponse billResponse = new BillResponse();
        billResponse.setMsg(String.valueOf(map.get("sub_msg")));
        if (AliPayConstants.SUCCESS_CODE.equals(code)) {
            billResponse.setData(executeResult);
            billResponse.setBillDownloadUrl(String.valueOf(map.get("bill_download_url")));
            return ResultWrapper.success(billResponse);
        } else {

            return ResultWrapper.fail(billResponse);
        }
    }
}
